package com.zhao.dota.security.integration.authenticator;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhao.dota.bo.AuthenticateUser;
import com.zhao.dota.model.User;
import com.zhao.dota.security.integration.IntegrationAuthentication;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 默认登录处理
 **/
@Component
@Primary
public class UsernamePasswordAuthenticator extends AbstractPreparableIntegrationAuthenticator {

    @Override
    public AuthenticateUser authenticate(IntegrationAuthentication integrationAuthentication) {
        LambdaQueryWrapper<User> query = Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, integrationAuthentication.getUsername());
        User user = userService.getOne(query);
        if (user == null) {
            throw new UsernameNotFoundException(integrationAuthentication.getUsername());
        }
        AuthenticateUser authenticateUser = new AuthenticateUser();
        authenticateUser.setUsername(integrationAuthentication.getUsername());
        authenticateUser.setPassword(user.getPassword());
        BeanUtils.copyProperties(user, authenticateUser);
        return authenticateUser;
    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) {

    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return StringUtils.isEmpty(integrationAuthentication.getAuthType());
    }
}
